package frontend;

import soenudp.Command;
import soenudp.UDPHelper;
import soenudp.UDPMessage;
import soenudp.UDPException;

public class FronEnd {

    /* IP Address is actually a bigger issue than the port number.
     * When a replica will become a leader, the IP will change.
     * 
     * Just use 127.0.0.1 for now, and start a DTRSManager.
     * I will make the DTRS ping the Front-end when he join a group as a leader.
     * This is will provide the front-end the correct IP Address. (registering)
     */
    static String IP_MTL_LEAD   = "127.0.0.1"; // Leader will have to PING the FE 1st (the same a registering)
    static String IP_TOR_LEAD   = "127.0.0.1";
    static int    LEAD_MTL_PORT = 20020;
    static int    LEAD_TOR_PORT = 20060;
    static UDPHelper udpClient;
    
    private static UDPMessage sendToDTRS(UDPMessage request)
    {
        UDPMessage response = null;
        
        try 
        {
            udpClient.sendToNode(IP_MTL_LEAD, LEAD_MTL_PORT, request);
            response = udpClient.getMessage();
        } catch (UDPException e) 
        {
            e.printStackTrace();
        }
        
        return response;
    }
   
    
    public static void main(String[] args) 
    {
        
        // This must be done prior to send/receive message 
        // START INIT
        udpClient = new UDPHelper();
        try {
            udpClient.startUnicastClient("FRONT_END_MTL");
        } catch (UDPException e) {
            e.printStackTrace();
        }  // END INIT
       
        
        // Refer to FakeFE.java in soendtrs/ or dtrs/ folder if you want more request examples.
        // For example if you get a RESERVE 10 tickets for MTL333 by CustID:111222 (CORBA Side),
        // you would dispatch the following: 
        UDPMessage request = new UDPMessage();
        request.command = Command.RESERVE;
        request.cust_id = "111222"; // CustID of the client
        request.show_id = "MTL333"; // ShowID the clien wish to reserve
        request.tickets = 10;       // How many tickets he wants
        
        // You can also use UDPMessage constructor:
        // ShowID, CustomerID, Tickets Amount, TransacID(optional for now), Optional Text */
        // UDPMessage request = new UDPMessage("MTL333", "111222", Command.RESERVE, 10,  0, null); 
        UDPMessage response = sendToDTRS(request);
       
        // You can dump the response on your screen:
        System.out.println(response);
        
        switch(response.command) 
        {
            case  ERROR:
                // Reply back to client an error
                // the message is in response.op_text
                break;
           
            case SUCCESS:
                // Reply back to client a successfull reservation / cancelation
                break;       
        }
    }



}
